﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Web.Mvc;
using viBook.Common;
using viBook.Models;

namespace viBook.ModelBinders
{
    public class ChapterModelBinder : DefaultModelBinder
    {
        protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
        {
            if (propertyDescriptor.Name == "Pages")
            {
                
                var filesUploadInfo = controllerContext.HttpContext.Request["fileUploadInfo"].Replace(controllerContext.HttpContext.Server.MapPath("~"), "/").Replace("\\", "/");
                var images = filesUploadInfo.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
              
                var pageCollection = images.Select(image => new Page
                                                                   {
                                                                       ImageSource = image
                                                                   }).ToList();
                propertyDescriptor.SetValue(bindingContext.Model, pageCollection);
                return;
            }

            if (propertyDescriptor.Name == "ChapterImage")
            {
                var chapter = bindingContext.Model as Chapter;
                var coverPage = Constant.DefaultChapterCover;
                if (chapter != null)
                {
                    var firstPage = chapter.Pages.FirstOrDefault();
                    if (firstPage != null)
                        coverPage = firstPage.ImageSource;
                }
                propertyDescriptor.SetValue(bindingContext.Model, coverPage);
                return;
            }

            if (propertyDescriptor.Name == "NumberOfPages")
            {
                var chapter = bindingContext.Model as Chapter;
                var numberOfPage = 0;
                if (chapter != null)
                {
                    numberOfPage = chapter.Pages.Count;
                }
                propertyDescriptor.SetValue(bindingContext.Model, numberOfPage);
                return;
            }
            base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
        }
    }
}